package com.ecar.api.support.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

public class Verification {
    public static BufferedImage getVerification(String phone){
        int width = 90;//定义图片的width  
        int height = 20;//定义图片的height  
        int countPage = 4;//定义图片上显示验证码的个数  

        int red = 0, green = 0, blue = 0;//颜色
        char[] codeSequence ={
                'a','b','c','d','e','f','g',
                'h','i','j','k','l','m','n',
                'o','p','q','r','s','t','u',
                'v','w','x','y','z','A','B',
                'C','D','E','F','G','H','I',
                'J','K','L','M','N','O','P',
                'Q','R','S','T','U','V','W',
                'X','Y','Z','1','2','3','4',
                '5','6','7','8','9','0'};
        BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        //相当于得到一支笔
        Graphics graphics=image.getGraphics();
        graphics.setColor(Color.white);
        graphics.fillRect(0, 0, 70, 30);
        Random random=new Random();
        graphics.setFont(new Font(Font.SERIF, Font.TYPE1_FONT, 20));
        String code="";
        for(int i=0;i<countPage;i++){
            int y = 10+random.nextInt(20); //10~30范围内的一个整数，作为y坐标
            String a=String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
            code+=a;
            // 产生随机的颜色值，让输出的每个字符的颜色值都将不同。
            red=random.nextInt(255);
            blue=random.nextInt(255);
            green=random.nextInt(255);
            graphics.setColor(new Color(red,blue,green));
            graphics.drawString(a, 5+i*width/4, y+2);
        }
        // 将四位数字的验证码保存到redis中。  
        Redis.c.setex(Redis.K.CODE.to(phone),3600,code);
        System.out.print(code);
        //随机生成干扰线
        for (int i=0;i<10;i++){
            graphics.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
            //把干扰线写入画板中
            graphics.drawLine(random.nextInt(width),random.nextInt(height),random.nextInt(width),random.nextInt(height));
        }
        //关闭画板，释放资源
        graphics.dispose();
        return image;

    }
}